import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_connect/http/src/utils/utils.dart';
import 'package:short_drama/models/Invite_model.dart';
import 'package:short_drama/utils/colors.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:short_drama/utils/http_util.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:short_drama/utils/validate.dart';
import 'package:short_drama/utils/float.dart';
import 'package:flutter/cupertino.dart';
import 'dart:async';

class ChangePage extends StatefulWidget {
  const ChangePage({Key? key}) : super(key: key);

  State<ChangePage> createState() => _ChangePageState();
}

class _ChangePageState extends State<ChangePage> {
  final TextEditingController _oldcontroller = TextEditingController(text: '');
  final TextEditingController _newcontroller = TextEditingController(text: '');
  final TextEditingController _codecontroller = TextEditingController(text: '');
  var countDown = 0.obs;
  Timer? timer;

  @override
  void initState() {
    super.initState();
    // _fetchData();
  }

  Future<void> _fetchData() async {
    try {
      final shareUrl = await InviteViewModel().fetchInviteData();
      setState(() {});
    } catch (e) {
      print('获取数据失败');
      setState(() {});
    }
  }

  void _doneAction() async {
    if (ValidateTool.validateChineseMobile(_newcontroller.text)) {
      final phone = _newcontroller.text;
      if (_codecontroller.text.length > 0) {
        ChangeViewModel().updatephone(phone, _codecontroller.text);
      } else {
        EasyLoading.showToast('请输入验证码');
      }
    } else {
      EasyLoading.showToast('请输入正确手机号');
    }
  }

  @override
  Widget build(BuildContext context) {
    final args = Get.arguments as Map<String, dynamic>;
    final oldPhone = args['phone'] ?? '';
    _oldcontroller.text = oldPhone;

    return Scaffold(
      backgroundColor: ClientColors.ff0a0f12,
      appBar: AppBar(
        iconTheme: IconThemeData(color: Colors.white),
        leading: IconButton(
          onPressed: () => {Get.back()},
          icon: Icon(Icons.arrow_back_ios),
        ),
        backgroundColor: ClientColors.odffffff,
        title: Text(
          '更换手机',
          style: TextStyle(color: Colors.white, fontSize: 18),
        ),
        centerTitle: false,
        titleSpacing: FloatConstance.navBarSpace,
        actions: [
          GestureDetector(
            onTap: () {
              _doneAction();
            },
            child: Container(
              margin: EdgeInsets.only(right: 10),
              child: Text(
                '完成',
                style: TextStyle(fontSize: 14, color: ClientColors.ff4abc9c),
              ),
            ),
          ),
        ],
      ),
      body: Column(
        children: [
          Container(
            height: 60,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(15),
              color: ClientColors.odffffff,
            ),

            child: Row(
              children: [
                Text(
                  '原手机号',
                  style: TextStyle(
                    color: ClientColors.f80FFFFFF,
                    fontSize: 15,
                    fontWeight: FontWeight.normal,
                  ),
                ),
                Spacer(),
                SizedBox(
                  height: 50,
                  width: 250,
                  child: TextField(
                    controller: _oldcontroller,
                    textAlign: TextAlign.right,
                    style: TextStyle(color: Colors.white),
                    decoration: InputDecoration(
                      hintText: oldPhone,
                      border: InputBorder.none,
                      fillColor: Colors.white,
                    ),
                    readOnly: true,
                    onChanged: (text) {},
                    onSubmitted: (text) {},
                  ),
                ),
              ],
            ).paddingSymmetric(horizontal: 16),
          ).marginOnly(top: 15, left: 16, right: 16),
          Container(
            height: 60,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(15),
              color: ClientColors.odffffff,
            ),

            child: Row(
              children: [
                Text(
                  '新手机号',
                  style: TextStyle(
                    color: ClientColors.f80FFFFFF,
                    fontSize: 15,
                    fontWeight: FontWeight.normal,
                  ),
                ),
                Spacer(),
                SizedBox(
                  height: 50,
                  width: 200,
                  child: TextField(
                    controller: _newcontroller,
                    textAlign: TextAlign.right,
                    style: TextStyle(color: Colors.white),
                    decoration: InputDecoration(
                      hintText: '新手机号',
                      border: InputBorder.none,
                    ),
                    onChanged: (text) {},
                    onSubmitted: (text) {},
                  ),
                ),
              ],
            ).paddingSymmetric(horizontal: 16),
          ).marginOnly(top: 15, left: 16, right: 16),
          Container(
            height: 60,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(15),
              color: ClientColors.odffffff,
            ),

            child: Row(
              children: [
                // Text(
                //   '验证码',
                //   style: TextStyle(
                //     color: ClientColors.f80FFFFFF,
                //     fontSize: 15,
                //     fontWeight: FontWeight.normal,
                //   ),
                // ),
                // SizedBox(width: 80),
                Expanded(
                  //height: 52,
                  child: SizedBox(
                    height: 52,
                    child: CupertinoTextField(
                      keyboardType: TextInputType.number,
                      placeholder: '验证码',
                      textAlign: TextAlign.left,
                      style: TextStyle(color: Colors.white),
                      placeholderStyle: TextStyle(color: Colors.white30),
                      decoration: BoxDecoration(
                        //borderRadius: BorderRadius.circular(12),
                        //color: Colors.white24,
                      ),
                      suffix: GestureDetector(
                        onTap: () {
                          if (countDown.value > 0) {
                            return;
                          }
                          if (_newcontroller.text.isEmpty) {
                            EasyLoading.showToast('请输入新手机号');
                            return;
                          } else if (!ValidateTool.validateChineseMobile(
                            _newcontroller.text,
                          )) {
                            EasyLoading.showToast('电话号码格式错误');
                            return;
                          }
                          querySms(_newcontroller.text);
                        },
                        child: SizedBox(
                          // width: 100,
                          child: Container(
                            height: 40,
                            width: 110,
                            padding: EdgeInsets.all(10),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(10),
                              color: Colors.white24,
                            ),
                            child: Text(
                              countDown.value <= 0
                                  ? '获取验证码'
                                  : '${countDown.value}',
                              textAlign: TextAlign.center,
                              style: TextStyle(color: Colors.white),
                            ),
                          ),
                        ),
                      ),
                      maxLines: 1,
                      onChanged: (value) {
                        _codecontroller.text = value;
                      },
                    ),
                  ),
                ),
              ],
            ).paddingSymmetric(horizontal: 16),
          ).marginOnly(top: 15, left: 16, right: 16),
        ],
      ),
    );
  }

  Future<void> querySms(String phone) async {
    EasyLoading.show(status: 'loading', maskType: EasyLoadingMaskType.clear);
    try {
      final result = await HttpUtil().post(
        'send/mobile/login',
        params: {"mobile": phone},
      );
      final dynamic responseData = result.data['data'];
      final String? token = responseData['token'] as String?;
      countDown.value = 60;
      startTime();
    } catch (e) {
      EasyLoading.showToast('请求失败');
    }
    EasyLoading.dismiss();
  }

  startTime() {
    if (timer != null) {
      stopTimer();
    }
    void callback() {
      if (countDown.value > 0) {
        setState(() {
          countDown.value -= 1;
        });
      } else if (countDown.value == 0) {
        stopTimer();
      }
    }

    timer = Timer.periodic(const Duration(seconds: 1), (Timer t) {
      callback();
    });
  }

  stopTimer() {
    timer!.cancel();
    timer = null;
  }
}

class ChangeViewModel {
  Future<void> updatephone(String phone, String mobile_code) async {
    try {
      final response = await HttpUtil().put(
        'member/mobile',
        params: {'mobile': phone, 'mobile_code': mobile_code},
      );

      final dynamic responseData = response.data['data'];
      final dynamic msg = response.data['msg'] ?? '提示';
      EasyLoading.showToast(msg);
    } catch (e) {
      throw '';
    }
  }
}
